import csv
import time
from datetime import datetime
from common import bin_storage, file_mgmt
from f12 import f12_processor




# get today's raw data
def run(hq, max_retry=3):
    print('--------- Starting f12 --------')
    start_time = time.time()
    p = []
    for code in hq.infoParamMap:
        p.append((code, "12"))
    res = hq.getInfo(p,  {'12': '财务分析'}, max_retry)
    with open('/home/ubuntu/f10_serverside/f12/res/res_' + datetime.today().strftime('%Y-%m-%d') + '.csv', 'w',
              newline='', encoding="utf-8-sig",
              errors="ignore") as csvfile:
        fieldnames = ['code', 'content', 'flag']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        writer.writeheader()
        for i in res:
            try:
                writer.writerow(i)
            except Exception as x:
                print('Error occurred when writing f12 res')
                print(str(x))

    print("--------------------- Starting f12 processing  --------------------")
    res.clear()
    u = file_mgmt.push(dir="/home/ubuntu/f10_serverside/f12/res")
    if u[1]:
        triplet_w_code = f12_processor.run(u[1])
        bin = bin_storage.Bin_storage()
        save_bin_name = '/home/ubuntu/f10_serverside/f12/bin/' + datetime.today().strftime('%Y-%m-%d')
        bin.save(save_bin_name, triplet_w_code)
        file_mgmt.push(dir="/home/ubuntu/f10_serverside/f12/bin")
    end_time = time.time()
    hours, rem = divmod(end_time - start_time, 3600)
    minutes, seconds = divmod(rem, 60)
    print("-------- f12 finished and cost {:0>2}:{:0>2}:{:05.2f}. -------".format(
        int(hours), int(minutes), seconds))


if __name__ == '__main__':
    run()
